﻿#region

using System.Configuration;
using System.Timers;
using System.Xml;
using CuongHanh.Helpers;
using CuongHanh.Models;
using CuongHanh.Service;

#endregion

namespace CuongHanh.Context
{
    public class TiGiaContext
    {
        public static readonly TiGiaContext Singleton = new TiGiaContext();

        private readonly Timer UpdateTimer = new Timer();

        public string LastUpdate = string.Empty;

        public TiGiaContext()
        {
            UpdateTigia();
            UpdateTimer.Interval = 10 * 60 * 1000; //10 minute
            UpdateTimer.Elapsed += UpdateTimer_Elapsed;
            UpdateTimer.Start();
        }

        private void UpdateTimer_Elapsed(object sender,
                ElapsedEventArgs e)
        {
            UpdateTigia();
        }

        private void UpdateTigia()

        {
            if(string.IsNullOrWhiteSpace(AppUtil.TiGiaUrl)
               && ConfigurationManager.AppSettings["TiGiaUrl"] != null)
                AppUtil.TiGiaUrl = ConfigurationManager.AppSettings["TiGiaUrl"];
            XmlDocument xmlDoc = XmlHelper.MakeRequest(AppUtil.TiGiaUrl);
            if(xmlDoc == null)
                return;
            XmlNodeList lastUpdate = xmlDoc.GetElementsByTagName("DateTime");
            LastUpdate = lastUpdate[0].InnerXml;
            XmlNodeList exrates = xmlDoc.GetElementsByTagName("Exrate");
            foreach (XmlElement item in exrates)
            {
                if(item.Attributes["CurrencyCode"].Value == "AUD"
                   || item.Attributes["CurrencyCode"].Value == "EUR"
                   || item.Attributes["CurrencyCode"].Value == "USD")
                {
                    TiGiaServce.Update(new TiGia(item));
                }
            }
        }
    }
}
